package org.shangda.wechat.pet.web.interceptor;

import com.alibaba.fastjson.JSONObject;
import org.shangda.wechat.pet.enums.ErrorCode;
import org.shangda.wechat.pet.util.ApplicationContextHolder;
import org.shangda.wechat.pet.util.Constants;
import org.shangda.wechat.pet.util.RedisCacheUtil;
import org.shangda.wechat.pet.web.vo.MemberSimpleInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.security.auth.login.LoginException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@Component
public class MiniAppInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        log.info("Controller Name:"+((HandlerMethod)handler).getBean().getClass().getName());
        log.info("Controller Method Name:"+((HandlerMethod)handler).getMethod().getName());
        String sessionId = request.getHeader(Constants.YOUNGOR_ZOO_MP_HEADER_KEY_TOKEN);
        if(StringUtils.isBlank(sessionId)){
            throw new LoginException(ErrorCode.LOGIN_ERROR.getMessage());
        }

        String sessionKey = Constants.MINIAPP_SESSION_KEY_PRE + sessionId;
        RedisCacheUtil redisCacheUtil = ApplicationContextHolder.getBean("redisCacheUtil");
        String member = redisCacheUtil.get(sessionKey);
        if(null == member){
            log.info("MiniAppInterceptor sessionId：" + sessionId);
            throw new LoginException(ErrorCode.LOGIN_ERROR.getMessage());
        }else{
            JSONObject memberJson = JSONObject.parseObject(member);
            MemberSimpleInfo memberSimpleInfo =new MemberSimpleInfo();
            memberSimpleInfo.setMemberId(memberJson.getInteger("memberId"));
            memberSimpleInfo.setSessionKey(memberJson.getString("sessionKey"));
            request.setAttribute(Constants.MINIAPP_MEMBER, memberSimpleInfo);
        }
        return true;
    }
}
